package com.yaowen.xmlreader;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by HelloWorld on 2015/9/22.
 */
public class DomHandler {
    public static void GetStringFromDom(InputSource inputSource){
        try {
            DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
            Document document=documentBuilder.parse(inputSource);
            //获取根节点
            Element rootElement=document.getDocumentElement();
            //获取第一级子节点
            NodeList nodeList=rootElement.getElementsByTagName("work");
            for (int i=0;i<nodeList.getLength();i++){
                //String work = rootElement.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
                Element workElement= (Element) nodeList.item(i);
                //获取节点中的属性值
                //String attr= workElement.getAttribute("XXX");
                //通过节点的标签名字来获取值
                String name=workElement.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
                String age=workElement.getElementsByTagName("age").item(0).getFirstChild().getNodeValue();
                System.out.println("----------startReade-------------");
                System.out.println("名字为："+name);
                System.out.println("年龄为："+age);
                System.out.println("----------endReader -------------");
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
